import { fetchResource } from './fetch-resource'

export const importHtml = async (url) => {
    const html = await fetchResource(url)
    const template = document.createElement('div')
    template.innerHTML = html

    // 提取脚本
    const scripts = template.querySelectorAll('script')
    const styles = Array.from(template.querySelectorAll('style, link[rel="stylesheet"]'))
        .map(style => {
            if (style.tagName.toLowerCase() === 'link') {
                // 对于外部样式表，需要加载它
                return fetchResource(style.href)
            }
            return style.textContent
        })
        .filter(Boolean)
        .join('\n')

    // 获取所有script标签代码
    function getExternalScripts() {
        return Promise.all(Array.from(scripts).map(script => {
            const src = script.getAttribute('src')
            if (!src) {
                return Promise.resolve(script.innerHTML)
            } else {
                return fetchResource(
                    src.startsWith('http') ? src : `${url}${src}`
                )
            }
        }))
    }

    // 执行所有脚本代码
    async function exeScripts() {
        const scripts = await getExternalScripts()
        let exports = {}
        scripts.forEach(code => {
            try {
                const module = { exports: {} }
                const moduleExec = (code) => {
                    eval(code)
                }
                moduleExec(code)
                exports = module.exports
            } catch (error) {
                console.warn('Script execution error:', error)
            }
        })
        return exports
    }

    return {
        template,
        getExternalScripts,
        exeScripts,
        styles
    }
}
